package com.rzt.cft.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rzt.cft.utils.CustomUtil;
import com.rzt.cft.dto.sys.SysRoleDto;
import com.rzt.cft.entity.sys.SysJob;
import com.rzt.cft.entity.sys.SysJobRole;
import com.rzt.cft.mapper.sys.SysJobMapper;
import com.rzt.cft.mapper.sys.SysJobRoleMapper;
import com.rzt.cft.service.sys.ISysJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 系统-岗位 服务实现类
 * </p>
 *
 * @author zhongzhong
 * @since 2019-12-31
 */
@Service
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {

    @Autowired
    private SysJobRoleMapper sysJobRoleMapper;

    @Override
    public List<SysRoleDto> jobRoleList(String jobId) {
        return CustomUtil.maping(baseMapper.jobRoleList(jobId), SysRoleDto.class);
    }

    @Transactional
    @Override
    public Boolean allotJobRole(String jobId, Collection<SysJobRole> itemList) {
        SysJob job = baseMapper.selectById(jobId);
        if (Objects.isNull(job)) {
            return false;
        }

        itemList.forEach(x -> x.setJobId(jobId));

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("job_id", jobId);
        // 原有分配项
        List<SysJobRole> oldList = sysJobRoleMapper.selectList(queryWrapper);

        // 已有角色标识集合
        List<String> oidList = CustomUtil.select(oldList, SysJobRole::getRoleId);
        // 当前角色标识集合
        List<String> itemIdList = CustomUtil.select(itemList, SysJobRole::getRoleId);

        // 新增项
        List<SysJobRole> newList = CustomUtil.where(itemList, x -> !oidList.contains(x.getRoleId()));
        // 删除项
        List<SysJobRole> delList = CustomUtil.where(oldList, x -> !itemIdList.contains(x.getRoleId()));

        List<String> didList = CustomUtil.select(delList, SysJobRole::getId);
        if (delList.size() > 0) {
            sysJobRoleMapper.deleteBatchIds(didList);
        }
        if (newList.size() > 0) {
            newList.forEach(x -> {
                sysJobRoleMapper.insert(x);
            });
        }
        return true;
    }
}
